package com.cn.dim.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.dim.pojo.Dep;
import com.cn.dim.pojo.Pages;
import com.cn.dim.pojo.User;
import com.cn.dim.service.UserService;
import com.cn.dim.utils.Md5Util;
import com.cn.dim.utils.TreeBuilder;
import com.github.pagehelper.Page;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;
	
	private User cUser=new User();//定义当前用户
	
	@RequestMapping(value ="/queryUser",method = RequestMethod.GET)
	@ResponseBody
	//Pages是自己定义的分页类，此方法用于显示用户列表
	public Map<String,Object> queryUser(HttpServletRequest request,User u,Pages pages,String roleid,String depid,String posid){
		cUser=(User)request.getSession().getAttribute("user");//从session中获取当前登录用户
		
		//参数u是列表页中以查询条件数据临时组成的过渡User对象
		Map<String,Object> param=new HashMap<>();//定义查询参数in
		Map<String,Object> reMap=new HashMap<>();//定义返回值，其中有一项必须是集合，先按照下面的写法做
		param.put("pageIndex", pages.getPage());
		param.put("pageSize", pages.getRows());
		param.put("user", u);
		param.put("roleid", roleid);
		param.put("depid", depid);
		param.put("posid", posid);
		
		try {
			Page<Map<String,Object>> rList = (Page)userService.queryUser(param);
			//下面代码通过循环对每一行的结果集补充“部门名称”与“职位名称”这两个显示字段
			for(Map m:rList){
				
				Map<String,Object> queryDepPosName_para=new HashMap<>();//定义queryDepPosName方法查询参数
				queryDepPosName_para.put("userid", m.get("id"));
				List<Map<String,Object>> depPosNames=userService.queryDepPosName(queryDepPosName_para);//返回值的List中只有一个Map元素
				String dName="";
				String pName="";
				for(Map depPosName:depPosNames){//实际上只循环一遍
					dName=dName+(String)depPosName.get("depname");
					pName=pName+(String)depPosName.get("posname");
				}
				m.put("depName", dName);//在每行记录中补充1个用于显示的部门名称的键值对
				m.put("posName", pName);//在每行记录中补充1个用于显示的职位名称的键值对
			}
			System.out.println(rList);
			reMap.put("rows", rList);
			reMap.put("total", rList.getTotal());
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/insertUser",method = RequestMethod.POST)
	@ResponseBody
	//此方法用于添加一个用户
	public Map<String,Object> insertUser(User u,String roleid,String depid,String posid)   //目前仅仅是单角色，单部门，单职位
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
		String userid=com.cn.dim.utils.StringUtil.makeUUID();
		u.setId(userid);//主键
		u.setIsdel("0");//构造删除标记位
		u.setIsused("0");//有效用户
		
        Map<String,Object> u_r=new HashMap<>();//构造用户角色中间表插入函数参数
        u_r.put("userid", userid);
        u_r.put("roleid", roleid);
        
        Map<String,Object> u_d_p=new HashMap<>();//构造用户部门职位中间表插入函数参数
        u_d_p.put("userid", userid);
        u_d_p.put("depid", depid);
        u_d_p.put("posid", posid);
		
		//这里补充创建人的id的代码
		u.setCreateuserid(cUser.getId());
		
        try 
		{
    		String defPassword=Md5Util.getEncryptedPwd("888888");//默认密码
    		u.setPassword(defPassword);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String cdate_s = sdf.format(new Date());//创建日期
			u.setCreatetime(cdate_s);

			int flag = userService.insertUser(u, u_r, u_d_p);
			if(flag>0)
			{
				reMap.put("message", "插入成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	//有子节点树形结构固定写法，不用太追究，此方法用于生成部门下拉树
	@RequestMapping(value ="/queryDep",method = RequestMethod.GET)
	//这里不用写@ResponseBody了
	public String queryDep(HttpServletResponse response){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();//这一句并没有使用上
		List<Dep> rList = new ArrayList<>();
		Map<String,Object> params = new  HashMap<>();
		try
		{
			rList =userService.queryDep(params);//这个params参数实际上没有用，是个空的摆设
			
			List<Dep> nodes = rList;
			String json  = new TreeBuilder().buildTree(nodes);
			
	        // 拼装树形json字符串
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(json);
			response.getWriter().flush();
		}
		catch (IOException e){
			e.getStackTrace();
		}
		return null;
	}
	
	//选择部门后职位联动下拉框
	@RequestMapping(value ="/queryPos",method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String,Object>> queryPos(HttpServletRequest request,String depid){
		Map<String,Object> param=new HashMap<>();//查询参数是部门depid；
		param.put("depid", depid);
		List<Map<String,Object>> list = new ArrayList<>();
		try {
			list =userService.queryPos(param);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}
	
	//该写角色下拉框获取函数了，写好了放在获取部门树形下拉框方法的上面；
	@RequestMapping(value ="/queryRole",method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String,Object>> queryRole(HttpServletRequest request){
		Map<String,Object> param=new HashMap<>();//查询不需要参数，这里作为一个空参数传过去；
		Map<String,Object> reMap=new HashMap<>();
		List<Map<String,Object>> list = new ArrayList<>();
		try {
			list =userService.queryRole(param);
//			reMap.put("data", list);
//			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
//			reMap.put("status", "error");
		}
		return list;
	}
	
	//根据参数中的userid取对应的部门，用于修改页面回显
	@RequestMapping(value ="/getDep",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> getDep(HttpServletRequest request,String userid){
		Map<String,Object> param=new HashMap<>();//查询参数是用户userid；
		Map<String,Object> reMap=new HashMap<>();
		param.put("userid", userid);
		try {
			List<Map<String,Object>> list =userService.getDep(param);
			reMap.put("data", list);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/updateUser",method = RequestMethod.POST)
	@ResponseBody
	//此方法用于添加一个用户
	public Map<String,Object> updateUser(User u,String userid,String roleid,String depid,String posid)   //目前仅仅是单角色，单部门，单职位
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
		
		Map<String, Object> m=new HashMap<>();//构造删除中间表所用到的参数userid键值对
		m.put("userid", userid);
        
		Map<String,Object> u_r=new HashMap<>();//构造用户角色中间表插入函数参数
        u_r.put("userid", userid);
        u_r.put("roleid", roleid);
        
        Map<String,Object> u_d_p=new HashMap<>();//构造用户部门职位中间表插入函数参数
        u_d_p.put("userid", userid);
        u_d_p.put("depid", depid);
        u_d_p.put("posid", posid);
        u.setId(userid);
		
		//这里补充修改（删除）人的id的代码
		u.setUpdateuserid(cUser.getId());
		
        try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String cdate_s = sdf.format(new Date());//修改（删除）日期
			u.setUpdatetime(cdate_s);
			
			int flag = userService.updateUser(u, m, u_r, u_d_p);
			if(flag>0)
			{
				reMap.put("message", "修改成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/delUser",method = RequestMethod.POST)//这个POST有待商榷
	@ResponseBody
	public Map<String,Object> delUser(HttpServletRequest request,String userid) 
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
        Map<String,Object> m=new HashMap<>();//构�?�service接口中delUser方法的参�?
        m.put("userid", userid);
		
		//这里补充修改（删除）人的id的代码
		m.put("updateuserid", cUser.getId());
		
		try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String cdate_s = sdf.format(new Date());//修改（删除）日期
	        m.put("updatetime", cdate_s);
			
			int flag = userService.delUser(m);
			if(flag>0)
			{
				reMap.put("message", "删除成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/queryUserById",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> queryUserById(HttpServletRequest request,String userid){
		Map<String,Object> m=new HashMap<>();
		Map<String,Object> reMap=new HashMap<>();
		m.put("userid", userid);
		try {
			User user =userService.queryUserById(m);
			reMap.put("data", user);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	//根据参数中的userid取对应的角色，用于修改页面回显
	@RequestMapping(value ="/getRole",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> getRole(HttpServletRequest request,String userid){
		Map<String,Object> param=new HashMap<>();//查询参数是用户userid；
		Map<String,Object> reMap=new HashMap<>();
		param.put("userid", userid);
		try {
			List<Map<String,Object>> list =userService.getRole(param);
			reMap.put("data", list);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/updatePassword",method = RequestMethod.POST)
	@ResponseBody
	//此方法用于添加一个用户
	public Map<String,Object> updatePassword(User u,String userid)
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
        u.setId(userid);
		
		//这里补充修改（删除）人的id的代码
		u.setUpdateuserid(cUser.getId());
		
        try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String cdate_s = sdf.format(new Date());//修改（删除）日期
			u.setUpdatetime(cdate_s);
			
			int flag = userService.updatePassword(u);
			if(flag>0)
			{
				reMap.put("message", "修改成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/getIndexPageInfo",method = RequestMethod.POST)
	@ResponseBody
	//新补充，此方法用于首页面用户信息的显示
	public Map<String,Object> getIndexPageInfo(HttpServletRequest request)
	{
		cUser=(User)request.getSession().getAttribute("user");//从session中获取当前登录用户
		Map<String,Object> reMap=new HashMap<>();//返回值map
        reMap.put("id", cUser.getId());
		reMap.put("name", cUser.getName());
		reMap.put("username",cUser.getUsername());
		return reMap;
	}
	
	@RequestMapping(value ="/testopenid",method = RequestMethod.POST)
	@ResponseBody
	//新补充，此方法用于首页面用户信息的显示
	public Map<String,Object> testopenid(HttpServletRequest request)
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
		Map<String,Object> m1=new HashMap<>();//调用的方法的参数
		Map<String,Object> m2=new HashMap<>();//调用的方法的参数
		m1.put("openid", "222");
		m2.put("openid", "111");
		boolean flag=userService.isWxAlreadyLogin(m1);//测试否
		User user=userService.getWxLoginUserByOpenid(m2);//测试可以取到
		reMap.put("t1", flag);
		reMap.put("t2", user.getName());
		Map<String,Object> m3=new HashMap<>();//调用的方法的参数
		Map<String,Object> m4=new HashMap<>();//调用的方法的参数
		m3.put("openid", "888");
		m3.put("userid", "08");
		m4.put("userid", "09");
		int i=userService.bindingOpenid(m3);
		if(i>0)
		{
			reMap.put("t3", "绑定openid成功");
		}
		int j=userService.wxLogOut(m4);
		if(j>0)
		{
			reMap.put("t4", "openid解绑成功");
		}
 		return reMap;
	}
	
}
